package cn.highedu.coolshark.account.security;

import cn.highedu.coolshark.account.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Slf4j
public class UserDetailsImpl implements UserDetails {

    private AdminLoginInfoVO admin;
    private List<GrantedAuthority> authorities = new ArrayList<>();

    /**
     * 构造方法，将AdminLoginInfoVO对象封装到UserDetailsImpl对象中
     *
     * @param admin AdminLoginInfoVO对象
     *              该对象封装了管理员的登录信息
     */
    public UserDetailsImpl(AdminLoginInfoVO admin) {
        this.admin = admin;
        //读取全部角色
        List<String> roles = admin.getRoles();

        //读取全部权限
        List<String> permissions = admin.getPermissions();
        //将角色和权限封装到authorities中
        if (roles != null){
            for (String role : roles) {
                authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
            }
        }
        log.debug("permissions: {}", permissions);
        if (permissions != null) {
            for (String permission : permissions) {
                authorities.add(new SimpleGrantedAuthority(permission));
            }
        }
    }

    public AdminLoginInfoVO getAdmin() {
        return admin;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return admin.getPassword();
    }

    @Override
    public String getUsername() {
        return admin.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return admin.getEnable() == 1;
    }

    @Override
    public String toString() {
        return "UserDetailsImpl{" +
                "admin=" + admin +
                ", authorities=" + authorities +
                '}';
    }
}
